<template>
  <div>
    <head-nev msg="黑马优购" :backState="true"></head-nev>
    <!-- 轮播图 -->
    <van-swipe :autoplay="3000" id="top">
      <van-swipe-item v-for="(image, index) in goodsInfo.pics" :key="index">
        <img v-lazy="image.pics_big_url" class="playImg" @click="getImg(index)" />
      </van-swipe-item>
    </van-swipe>
    <!-- 价格 -->
    <van-row class="price" type="flex">
      <span v-if="goodsInfo.goods_price">{{'￥'+goodsInfo.goods_price}}</span>
    </van-row>
    <!-- 商品名 -->
    <van-row type="flex" class="introduce">
      <van-col span="20" class="goodsTitle">{{goodsInfo.goods_name}}</van-col>
      <van-col span="4">
        <van-row type="flex" justify="center">
          <van-icon name="star-o" />
        </van-row>
        <van-row type="flex" justify="center">
          <span>收藏</span>
        </van-row>
      </van-col>
    </van-row>
    <!-- 快递费 -->
    <van-row class="express" type="flex">快递：免运费</van-row>
    <van-row class="devide-normal"></van-row>
    <van-row class="express" type="flex">促销：满300元减30元</van-row>
    <!-- 购物车栏 -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" />
      <van-goods-action-icon icon="cart-o" text="购物车" :info="total" @click="GoCart" />
      <van-goods-action-button type="warning" text="加入购物车" @click="addCart" />
    </van-goods-action>
    <van-row class="devide-light"></van-row>
    <van-cell is-link id="address" @click="onAddress">
      <span class="addressText">送至</span>
      <span v-if="!addressSelected">请选择收货地址</span>
      <span v-else>{{addressSelected}}</span>
    </van-cell>
    <van-row class="devide-normal"></van-row>
    <!-- 图文详情——规格参数 -->
    <van-tabs v-model="activeName" class="tabs">
      <van-tab title="图文详情" name="imgText">
        <div v-html="goodsInfo.goods_introduce" class="tabImg"></div>
      </van-tab>
      <van-tab title="规格参数" name="param">
        <van-row class="attrsRow">
          <van-col span="12" class="attrcol">
            <div
              class="attrname"
              v-for="(item,index) in goodsInfo.attrs"
              :key="index"
              v-text="item.attr_name"
            ></div>
          </van-col>
          <van-col span="12" class="attrcol">
            <div
              class="attrvals"
              v-for="(item,index) in goodsInfo.attrs"
              :key="index"
              v-text="item.attr_vals"
            ></div>
          </van-col>
        </van-row>
      </van-tab>
    </van-tabs>
    <!-- 地址弹出框 -->
    <van-action-sheet
      v-model="addressShow"
      :actions="addressList"
      @select="onSelectAddress"
      title="配送至"
      close-on-click-action
    >
    <van-button round type="danger" class='addressButton' to='/address' v-if = '!addressSelected' >新增地址</van-button>
    <van-button round type="danger" class='addressButton' to='/address' v-else >选择其它地址</van-button>
    </van-action-sheet>
  </div>
</template>

<script>
import Vue from 'vue'
import { ImagePreview } from 'vant'
import { log } from 'util'
import { lemonchiffon } from 'color-name'
Vue.use(ImagePreview)
export default {
  data() {
    return {
      goodsId: 0,
      goodsInfo: {},
      pics: [],
      picPreview: [],
      goods2Cart: {
        checked: false,
        goods_name: '',
        goods_price: 0,
        goods_small_logo: '',
        goods_amount: 0
      },
      activeName: 'a',
      catesList: [],
      total: 0,
      attrs: [],
      addressShow: false,
      addressList: [],
      addressSelected: ''
    }
  },
  created() {
    this.getGoodsId()
    this.getGoods()
    this.togeImg()
    this.goodsTotal()
    this.getAddress()
  },
  methods: {
    //获取商品ID
    getGoodsId() {
      this.goodsId = this.$route.params.id
    },
    //处理localStorage中的地址信息
    getAddress() {
      const addList = JSON.parse(localStorage.getItem('arr'))
      const addressId = JSON.parse(localStorage.getItem('chosenAddressId'))
      //根据id找到目前默认的地址
      if (addList ==null) return
      const nowAddres = addList.filter(item => item.id == addressId)
      //处理地址信息给到上拉菜单需要的格式的数组
      let addressArr = []
      addList.forEach(item => addressArr.unshift({ name: item.address }))
      this.addressList = addressArr
      this.addressSelected = nowAddres[0].address
      // console.log(this.addressList)
    },
    //获取图片拼接成数组
    togeImg() {
      const imgArr = []
      this.pics.forEach(item => imgArr.push(item.pics_big_url))
      this.picPreview = imgArr
    },
    //图片预览
    getImg(index) {
      ImagePreview({
        images: this.picPreview,
        showIndex: true,
        loop: false,
        startPosition: index
      })
    },
    //根据商品ID获取商品数据
    async getGoods() {
      const { data: res } = await this.$http.get('/goods/detail', {
        params: { goods_id: this.goodsId }
      })
      this.goodsInfo = res.message
      // console.log(res.meta.status);
    if(res.meta.status !== 200) return
      this.pics = res.message.pics
      // console.log(this.goodsInfo)
      this.togeImg()
    },
    //点击购物车，跳转购物车界面
    GoCart() {
      this.$router.push('/cart')
    },
    //点击加入购物车
    addCart() {
      //将购物车页面所需要的数据放入一个对象中
      this.goods2Cart.goods_name = this.goodsInfo.goods_name
      this.goods2Cart.goods_price = this.goodsInfo.goods_price
      this.goods2Cart.goods_small_logo = this.goodsInfo.goods_small_logo
      this.goods2Cart.goods_id = this.goodsId
      // console.log(this.goods2Cart.goods_id)
      //如果没有向catesLlist中添加过商品
      if (localStorage.getItem('goodsIncate') === null) {
        this.goods2Cart.goods_amount = 1
        this.catesList.unshift(this.goods2Cart)
        localStorage.setItem('goodsIncate', JSON.stringify(this.catesList))
      }
      //如果添加过的话，获取localStorage中的数据
      else {
        const savedGoods = JSON.parse(localStorage.getItem('goodsIncate'))
        const i = savedGoods.findIndex(
          item => item.goods_id == this.goods2Cart.goods_id
        )
        //如果此商品第一次添加，直接向savedGoods中添加后存入localstorage
        if (i == -1) {
          this.goods2Cart.goods_amount = 1
          savedGoods.unshift(this.goods2Cart)
          localStorage.setItem('goodsIncate', JSON.stringify(savedGoods))
        }
        //如果被添加过，把该项商品数量加1添加后存入localstorage
        else {
          savedGoods[i].goods_amount++
          localStorage.setItem('goodsIncate', JSON.stringify(savedGoods))
        }
      }
      this.goodsTotal()
    },
    //商品总数
    goodsTotal() {
      if (localStorage.getItem('goodsIncate') === null) {
        this.total = 0
      } else {
        const savedGoods = JSON.parse(localStorage.getItem('goodsIncate'))
        let n = 0
        savedGoods.forEach(item => (n += item.goods_amount))
        this.total = n
      }
    },
    //点击选择地址菜单
    onAddress() {
      this.addressShow = true
    },
    // 选中弹出框中的地址
    onSelectAddress(chosen) {
      this.addressSelected = chosen.name
      const addList = JSON.parse(localStorage.getItem('arr'))
      let chosenId = null
      addList.forEach(item => {
        if (item.address == chosen.name) {
          chosenId = item.id
        }
      })
     localStorage.setItem('chosenAddressId', chosenId)
      //将localstore中的地址id值改为当前选中项的id
    }
  }
}
</script>

<style>
.playImg {
  height: 400px;
  width: 100%;
}
.van-swipe__indicators {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.7);
  width: 100%;
  height: 0.8rem;
  bottom: 0.16rem;
  text-align: center !important;
}
.price {
  align-items: center;
  color: red;
  font-family: 'Times New Roman';
  font-size: 26px;
  height: 50px;
  margin-left: 8px;
}
.introduce {
  font-size: 14px;
  padding: 0 10px;
  height: 55px;
  align-items: center;
}
.goodsTitle {
  font-family: '微软雅黑';
  border-right: solid 1px #f3f3f3;
}
.express {
  font-family: '微软雅黑';
  align-items: center;
  height: 1rem;
  margin-left: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #3c3e40;
}
.devide-normal {
  height: 5px;
  background-color: #efefef;
}
.devide-light {
  height: 3px;
  background-color: #efefef;
}
#address {
  font-size: 14px;
  padding: 0.25rem 0.21333rem;
  font-family: '微软雅黑';
}
.addressText {
  margin-right: 13px;
}
.van-goods-action {
  z-index: 99;
}
.attrname {
  height: 1.3rem;
  border-bottom: 1px solid #efefef;
  border-right: 1px solid #efefef;
  font-size: 12px;
  text-indent: 10px;
  line-height: 1.3rem;
  white-space: nowrap;
  overflow: hidden;
}
.attrvals {
  height: 1.3rem;
  border-bottom: 1px solid #efefef;
  font-size: 12px;
  text-indent: 10px;
  line-height: 1.3rem;
  white-space: nowrap;
  overflow: hidden;
}
.addressButton{
    width: 100%;
}
/* .van-popup{
    min-height: 200px;
} */
</style>